//
//  LXDepositApplyViewController.m
//  ZuLinProject
//
//  Created by bancheng on 2021/12/24.
//  Copyright © 2021 LX_App. All rights reserved.
//

#import "LXLoanApplyViewController.h"
#import "LXTableViewCell.h"
#import "LXChooseBtnTableViewCell.h"
#import "LXLoanModel.h"
#import "LXLoanPlanTableViewCell.h"
#import "LXLoanPlanRepaymentView.h"
#import "LXCooperationListViewController.h"
#import "LXCooperationModel.h"
#import "LXRemarkTabelViewCell.h"
@interface LXLoanApplyViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic) UITableView *tableView;
@property (nonatomic) NSMutableArray *data;
@property (nonatomic) NSMutableDictionary *loanDic;
@property (nonatomic) NSDictionary *selDic;


/**支付计划表*/
@property (nonatomic) NSMutableArray *payPlanAry;

@property (nonatomic) NSArray *periodsData; // 分期数据源
@property (nonatomic) NSInteger periods; // 分期  12期24期36期

@property (nonatomic) NSString *duoDate; // 付款日
@property (nonatomic) NSString *payeeCompanyId; // 收款公司id


@end

@implementation LXLoanApplyViewController
- (void)viewDidLoad {
    [super viewDidLoad];

    
    
    [self.tableView registerClass:[LXTableViewCell class] forCellReuseIdentifier:NSStringFromClass([LXTableViewCell class])];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LXLoanPlanTableViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([LXLoanPlanTableViewCell class])];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LXRemarkTabelViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([LXRemarkTabelViewCell class])];

    
    
    
    self.view.backgroundColor = White_Color;
    [self.view addSubview:self.tableView];
    
    [self loadData];
    
    if (self.type == 1) {
        [self setBottomViewWithText:@"确认新增"];
        [self layoutCustomNav:self.view title:@"新增贷款车辆"];

    }
    else {
        [self setBottomViewWithText:@"确认修改"];
        [self layoutCustomNav:self.view title:@"修改贷款车辆"];

    }
    
    
    
}
- (void)loadData{
    
    self.loanDic  = [NSMutableDictionary dictionary];
    
    self.periods = 12;
    
    // 模型为空,说明从车辆详情进入
    if (!ObjectIsEmpty(self.loanModel)) {

        // 车牌号
        [self.loanDic setValue:self.loanModel.carNumber forKey:@"carNumber"];
        [self.loanDic setValue:self.loanModel.carModel forKey:@"carModel"];

    
        // 修改的时候需要带入数据
        if (self.type==2) {
            
            //分期期数
            self.periods = self.loanModel.periods;
            [self.loanDic setValue:[NSString stringWithFormat:@"%@",@(self.loanModel.periods)] forKey:@"periodsShow"];
            //剩余期数
            [self.loanDic setValue:[NSString stringWithFormat:@"%@",@(self.loanModel.totalPeriods - self.loanModel.paidPeriods)] forKey:@"periodsShengYu"];
            //收款公司
            [self.loanDic setValue:self.loanModel.payeeCompanyName forKey:@"payeeCompanyName"];
            self.payeeCompanyId = self.loanModel.payeeCompanyId;
            //合约开始
            [self.loanDic setValue:self.loanModel.pactStartTime forKey:@"pactStartTime"];
            //合约结束
            [self.loanDic setValue:self.loanModel.pactEndTime forKey:@"pactEndTime"];
            
            //每月还款日
            self.duoDate = self.loanModel.duoDate;
            [self.loanDic setValue:[NSString stringWithFormat:@"%@日",self.loanModel.duoDate] forKey:@"duoDate"];
            //月付款
            [self.loanDic setValue:[NSString toTen:self.loanModel.monthlyPayment] forKey:@"monthlyPayment"];
            //首付款
            [self.loanDic setValue:[NSString toTen:self.loanModel.firstPay] forKey:@"firstPay"];
            //计划表
            self.payPlanAry = [NSMutableArray arrayWithArray:self.loanModel.paymentList];
            //创建日期
            [self.loanDic setValue:[self.loanModel.createTime length]>=10?[self.loanModel.createTime substringToIndex:10]:self.loanModel.createTime forKey:@"createTime"];
            
            [self.loanDic setValue:self.loanModel.remark forKey:@"remark"];


        }



    }

    NSArray *ary0 = @[
         
           @{
               @"title":@"车牌号",
               @"key":@"carNumber",
               @"height":@(kComHeight)
           },
           @{
               @"title":@"品牌型号",
               @"key":@"carModel",
               @"height":@(kComHeight)
           },
           @{
               @"title":@"分期期数",
               @"key":@"periods",
               @"height":self.type==1?@([LXChooseBtnTableViewCell height:self.periodsData]):@(0),
               @"canEdit":self.type==1?@(YES):@(NO),
           },
           @{
               @"title":@"分期期数",
               @"key":@"periodsShow",
               @"height":self.type==1?@(0):@(kComHeight),
               @"canEdit":@(NO),
           },
           @{
               @"title":@"剩余期数",
               @"key":@"periodsShengYu",
               @"height":self.type==1?@(0):@(kComHeight),
               @"canEdit":@(NO),
           },
           @{
               @"title":@"收款公司",
               @"key":@"payeeCompanyName",
               @"placeHolder" : @"请选择收款公司",
               @"sel":self.type==1?@"clickCompanyAction":@"",
               @"showAccess":self.type==1?@(YES):@(NO),
               @"height":@(kComHeight)
           },
         
           @{
               @"title":@"合约开始日期",
               @"key":@"pactStartTime",
               @"placeHolder" : @"请选择合约开始日期",
               @"canEdit":@(NO),
               @"showAccess":self.type==1?@(YES):@(NO),
               @"sel":self.type==1?@"clickPactStartAction":@"",
               @"height":@(kComHeight)
           },
           @{
               @"title":@"合约结束日期",
               @"key":@"pactEndTime",
               @"placeHolder" : @"请选择合约结束日期",
               @"canEdit":@(NO),
               @"showAccess":@(NO),
               @"sel":self.type==1?@"clickPactEndAction":@"",
               @"height":@(kComHeight)
           },
           @{
               @"title":@"每月还款日",
               @"key":@"duoDate",
               @"placeHolder" : @"请选择每月还款日",
               @"canEdit":@(NO),
               @"showAccess":self.type==1?@(YES):@(NO),
               @"sel":self.type==1?@"clickDuoDateAction":@"",
               @"height":@(kComHeight)
           },
           @{
               @"title":@"首付款(元)",
               @"key":@"firstPay",
               @"placeHolder" : @"请输入首付款",
               @"canEdit":self.type==1?@(YES):@(NO),
               @"showAccess":@(NO),
               @"inputType":@(NUM_DECIMAL),
               @"keyboardType":@(UIKeyboardTypeDecimalPad),
               @"maxLength":@(10),
               @"height":@(kComHeight)
           },
           @{
               @"title":@"每月还款金额(元)",
               @"key":@"monthlyPayment",
               @"placeHolder" : @"请输入每月还款金额",
               @"canEdit":self.type==1?@(YES):@(NO),
               @"showAccess":@(NO),
               @"inputType":@(NUM_DECIMAL),
               @"keyboardType":@(UIKeyboardTypeDecimalPad),
               @"maxLength":@(10),
               @"sel":@"",
               @"height":@(kComHeight)
           },
           @{
               @"title":@"创建日期",
               @"key":@"createTime",
                @"canEdit":@(NO),
               @"showAccess":@(NO),
               @"height":self.type==2?@(kComHeight):@(0)
           },
    ];
    
    [self.data addObject:ary0];
    
    NSArray *ary1 = @[
        @{
            @"title":@"还款计划",
            @"key":@"planForm",
            @"canEdit":self.type==1?@(YES):@(NO),
            @"height":@([LXLoanPlanTableViewCell getHeight:self.loanModel.paymentList])
        }
    ];
    [self.data addObject:ary1];
    
    
    NSArray *ary2 = @[
        @{
            @"title":@"备注",
            @"key":@"remark",
            @"height":@(150)
        }
    ];
    [self.data addObject:ary2];
    
    
  
    
    
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.data.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.data[section] count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.data[indexPath.section][indexPath.row];
    if ([dic[@"key"] isEqualToString:@"planForm"]&&self.type==1) {
        return [LXLoanPlanTableViewCell getHeight:self.payPlanAry];
    }
    return [dic[@"height"] doubleValue];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSDictionary *dic = self.data[indexPath.section][indexPath.row];
    if([dic[@"key"]  isEqualToString:@"remark"]){
        
        // 备注
        LXRemarkTabelViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXRemarkTabelViewCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setClipsToBounds:YES];
        cell.textView.placeholder = @"请输入备注...";
        cell.textView.maxLength = 200;
        cell.remarkTitle.text = @"备注";
        cell.textView.text = self.loanDic[@"remark"];
        [cell setTextViewEdit:^(NSString * _Nonnull textStr) {
            [self.loanDic setValue:textStr forKey:@"remark"];
        }];
        return cell;
    }
    
    // 租金计划表
    else if([dic[@"key"]  isEqualToString:@"planForm"]){
    
        
        
        if ([dic[@"canEdit"] boolValue]) {
            
            LXLoanPlanTableViewCell *cell = [[LXLoanPlanTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass([LXLoanPlanTableViewCell class]) WithData:!ObjectIsEmpty(self.payPlanAry)?self.payPlanAry:[NSMutableArray array] IsShow:NO];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell setClipsToBounds:YES];
            cell.titleLab.text = dic[@"title"];
            
    
            [cell setClickBtnAction:^(LXLoanModel * _Nonnull model) {
                
                [self showPlanViewWithModel:model];
            }];
            
            return cell;
        }
        else {
    
            LXLoanPlanTableViewCell *cell = [[LXLoanPlanTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass([LXLoanPlanTableViewCell class]) WithData:self.payPlanAry  IsShow:YES];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell setClipsToBounds:YES];
            cell.titleLab.text = dic[@"title"];
            return cell;
           
        }
        
   }
    // 提车状态
    if ([dic[@"key"] isEqualToString:@"periods"]) {
       
        NSArray *tempAry = self.periodsData;
    

       LXChooseBtnTableViewCell *cell = [[LXChooseBtnTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass([LXChooseBtnTableViewCell class]) WithData:tempAry];

       cell.selectionStyle = UITableViewCellSelectionStyleNone;
       [cell setClipsToBounds:YES];
        cell.canEdit = [dic[@"canEdit"] boolValue];
        
       cell.titleLab.text = dic[@"title"];
       [cell setClickBtnBlock:^(NSInteger Id) {
           self.periods = Id;
           
           [self countDate];
           
           [self payPlanAction];
           
           
       }];
       
       
       return cell;
    }
    
    
    LXTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXTableViewCell class])];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setClipsToBounds:YES];
    

    cell.cellDic = dic;
    cell.textFiled.hidden = NO;
    cell.subTitleLab.hidden = YES;
    cell.textFiled.text = self.loanDic[dic[@"key"]];
    

    cell.textfiledChangeBlock = ^(NSString * _Nonnull textStr) {
        self.loanDic[dic[@"key"]]  = textStr;
    

        if ([dic[@"key"] isEqualToString:@"monthlyPayment"]) {
            [self payPlanAction];
        }
        
    };
    
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary *dic = self.data[indexPath.section][indexPath.row];
    self.selDic = dic;
    NSString * selName = dic[@"sel"];
    SEL action = NSSelectorFromString(selName);
    if ([self respondsToSelector:action]) {
        [self performSelector:action withObject:nil afterDelay:0];
    }

}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *vv = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 30)];
    vv.backgroundColor = [UIColor colorWithHexString:@"#F7F8FA"];
    return vv;
}
//MARK: 计算结束日期
-(void)countDate{
    if (!StringIsEmpty(self.loanDic[@"pactStartTime"])) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyy-MM-dd";
        NSDate *date = [formatter dateFromString:self.loanDic[@"pactStartTime"]];
        NSString *pactEndTime = [NSString getCustomDateFromDate:date withMonth:self.periods];
        [self.loanDic setValue:pactEndTime forKey:@"pactEndTime"];
        [self.tableView reloadData];
    }
}
#pragma mark -- 选择合约开始日期
-(void)clickPactStartAction{
    [self.view endEditing:YES];
    DatePickView *datePicker =[[DatePickView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withDateStr:self.loanDic[@"pactStartTime"] withIsMaxDate:YES withNoForward:NO WithTips:@"请选择合约开始日期"] ;
    [datePicker showBoomView];
    [[[UIApplication sharedApplication].delegate window] addSubview:datePicker];
    WEAKSELF
    datePicker.block = ^(NSString *yearString){
        
        [weakSelf.loanDic setObject:yearString forKey:weakSelf.selDic[@"key"]];

        
        [weakSelf countDate];
        
        
        NSString *duoDate =  [NSString stringWithFormat:@"%@日",@([[yearString substringFromIndex:yearString.length - 2] intValue])];
        [self.loanDic setValue:duoDate forKey:@"duoDate"];
        
        self.duoDate = [yearString substringFromIndex:yearString.length - 2];
        
        
//        self.duoDate = self.loanModel.duoDate;
//        [self.loanDic setValue:[NSString stringWithFormat:@"%@日",self.loanModel.duoDate] forKey:@"duoDate"];

        
        
        [self payPlanAction];

    };
}
#pragma mark -- 选择付款日
-(void)clickDuoDateAction{
    [self.view endEditing:YES];
    DatePickView *datePicker =[[DatePickView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withDateStr:self.duoDate withIsMaxDate:YES withNoForward:NO WithTips:@"请选择还款日"] ;
    [datePicker showBoomView];
    [[[UIApplication sharedApplication].delegate window] addSubview:datePicker];
    WEAKSELF
    datePicker.block = ^(NSString *yearString){

        // 如果号数大于28号,就截止到28号
        if ([[yearString substringFromIndex:yearString.length-2] intValue]>28) {
            yearString  = @"28";
        }
        else {
            yearString = [NSString stringWithFormat:@"%@",@([[yearString substringFromIndex:yearString.length-2] intValue])];
        }
        
        self.duoDate = yearString;
        [weakSelf.loanDic setObject:[NSString stringWithFormat:@"%@日",yearString] forKey:weakSelf.selDic[@"key"]];
        [weakSelf.tableView reloadData];
        
        
        [self payPlanAction];
        
        
    };
}
-(void)clickCompanyAction{
    LXCooperationListViewController *vc = [[LXCooperationListViewController alloc] init];
    vc.type = 2;
    [vc setClickVcCallBlock:^(LXCooperationModel * _Nonnull model) {
        
        [self.loanDic setValue:model.name forKey:@"payeeCompanyName"];
        self.payeeCompanyId = model.ID;
        [self.tableView reloadData];
    }];
    [self pushToNextController:vc];
}

- (NSMutableArray *)data{
    if (!_data) {
        _data = [[NSMutableArray alloc]init];
    }
    return _data;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kViewTopHeight, ScreenWidth, kScreenHeight - kViewTopHeight - kComHeight - 10) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = ColorWithF7F8FA;
        _tableView.sectionFooterHeight = 10;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}




#pragma mark ---- 确认新增/修改点击事件
- (void)clickBottomView:(UIButton *)sender{
    
   
    if (StringIsEmpty(self.loanDic[@"payeeCompanyName"])) {
        showAlert(@"请选择收款公司");
        return;
    }
    if (StringIsEmpty(self.loanDic[@"pactStartTime"])) {
        showAlert(@"请选择合约开始时间");
        return;
    }
    if (StringIsEmpty(self.loanDic[@"duoDate"])) {
        showAlert(@"请选择每月还款日");
        return;
    }
    if (StringIsEmpty(self.loanDic[@"firstPay"])) {
        showAlert(@"请输入首付款");
        return;
    }
    if ([self.loanDic[@"firstPay"] doubleValue] == 0) {
        showAlert(@"首付款不能为0");
        return;
    }
    if (StringIsEmpty(self.loanDic[@"monthlyPayment"])) {
        showAlert(@"请输入每月还款金额");
        return;
    }
    if ([self.loanDic[@"monthlyPayment"] doubleValue] == 0) {
        showAlert(@"每月还款金额为0");
        return;
    }
    
    
    [Tool showAlertTitle:@"是否确认提交" msg:nil cancelTitle:@"取消" commitBtnTitle:@"确定" cancelHandlerBlock:^{
    } commitHandlerBlock:^{
        
        
        NSMutableArray *paymentList = [NSMutableArray array];
        
        for (LXLoanModel *mm in self.payPlanAry) {
            
            NSDictionary *dic = @{
                @"amount":mm.amount,
                @"exceptPaidDate":mm.exceptPaidDate,
                @"remark":mm.remark,
                @"period":mm.period
            };
            [paymentList addObject:dic];
        }
        
        
        NSMutableDictionary *dic = @{
            
            @"carId":self.loanModel.carId, // 所属车辆id
            @"carNumber":self.loanModel.carNumber,// 所属车辆车牌号
            @"carModel":self.loanDic[@"carModel"],// 品牌
            @"periods":@(self.periods),// 期数
            @"payeeCompanyName":self.loanDic[@"payeeCompanyName"],//  收款公司
            @"payeeCompanyId":self.payeeCompanyId,//  收款公司id
            @"pactStartTime":self.loanDic[@"pactStartTime"], //  合约开始日期
            @"pactEndTime":self.loanDic[@"pactEndTime"], //  合约结束日期
            @"duoDate":self.duoDate, //  每月还款日期
            @"firstPay":self.loanDic[@"firstPay"], //  首付金额
            @"monthlyPayment":self.loanDic[@"monthlyPayment"], //  月付金额
            @"paymentList":paymentList, //  计划表
            @"remark":self.loanDic[@"remark"]
            
        }.mutableCopy;
        
        
        
        NSString *url;
        if (self.type == 1) {
            url = POST_AddTbuycayloan;
        }
        else
        {
            url = POST_UpdateTbuycayloan;
            [dic setValue:self.loanModel.ID forKey:@"id"];
        }
        [MSNetworkManager postRevertUrl:url params:dic success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
            
            if (isSuccess) {
                if (self.type==1) {
                    showAlert(@"新增贷款成功");
                }
                else {
                    showAlert(@"修改贷款成功");
                }
               
                
                // carModel 有值说明从详情页进入,返回时须刷新列表
                if (!ObjectIsEmpty(self.loanModel)) {
                    kUserDefaultSetBool(YES, kRefreshStr);
                }
                [self.navigationController popViewControllerAnimated:YES];
            }
            
        } failure:^(NSUInteger code, NSString * _Nonnull message) {
        } withShowHud:YES];
    } onVC:self];
    
 
}



#pragma mark -- 期数数据源
- (NSArray *)periodsData{
    _periodsData = @[

        @{
            @"title":@"12期",
            @"sel":@(NO),
            @"id":@(12)
        }.mutableCopy,
        @{
            @"title":@"24期",
            @"sel":@(NO),
            @"id":@(24)
        }.mutableCopy,
        @{
            @"title":@"36期",
            @"sel":@(NO),
            @"id":@(36)
        }.mutableCopy,
    ];

    for (NSMutableDictionary *dic in _periodsData) {
        if ([dic[@"id"] integerValue] == self.periods) {
            [dic setValue:@(YES) forKey:@"sel"];
            break;
        }
    }

    return _periodsData;
}

// MARK: 租金支付计划表
-(void)payPlanAction{
    
    
    if (StringIsEmpty(self.loanDic[@"monthlyPayment"]) ||
        StringIsEmpty(self.duoDate)||
        StringIsEmpty(self.loanDic[@"pactStartTime"])||
        StringIsEmpty(self.loanDic[@"pactEndTime"])) {
        return;
    }
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd";
    NSString *nextYY = [self.loanDic[@"pactStartTime"] componentsSeparatedByString:@"-"][0];
    NSString *nextMM = [self.loanDic[@"pactStartTime"] componentsSeparatedByString:@"-"][1];
    NSDate *date = [formatter dateFromString:[NSString stringWithFormat:@"%@-%@-%02d",nextYY,nextMM,[self.duoDate intValue]]];

    NSMutableArray *ary = [NSMutableArray array];
    for (int i = 0; i<self.periods; i++) {

        NSString *nowDate = [NSString getCustomDateFromDate:date withMonth:1 * i];
        
        NSDictionary *dic = @{
            @"exceptPaidDate":nowDate,
            @"amount":self.loanDic[@"monthlyPayment"],
            @"remark":[NSString stringWithFormat:@"第%d期贷款",i+1],
            @"period":@(i+1),
        };
        [ary addObject:dic];
    }


    self.payPlanAry = [LXLoanModel mj_objectArrayWithKeyValuesArray:ary];
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:self.data.count-2]  withRowAnimation:UITableViewRowAnimationNone];
}
// MARK: 修改还款计划
-(void)showPlanViewWithModel:(LXLoanModel *)model{
    LXLoanPlanRepaymentView *vc = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([LXLoanPlanRepaymentView class]) owner:nil options:nil].firstObject;
    vc.model = model;
    vc.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
    [self.view addSubview:vc];


    [vc setClickPlanAction:^(LXLoanModel * _Nonnull mm) {

        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:self.data.count-2]  withRowAnimation:UITableViewRowAnimationNone];

    }];
  
    
    
}


@end
